package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.SysServerMapper;
import com.example.po.SysServer;
import com.example.utils.IPUtils;
import com.example.utils.RandomUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/****
 * 获取服务节点
 */
@Service
public class SysServerServiceImpl extends ServiceImpl<SysServerMapper, SysServer> implements SysServerService {

    @Resource
    private ApplicationContext applicationContext;

    private String host;

    private long port = 0;

    private long serverKey = 0;

    @Override
    public String getHost() {
        if (StringUtils.isEmpty(host)) {
            this.host = IPUtils.getIP();
        }
        return this.host;
    }

    @Override
    public long getPort() {
        if (this.port == 0) {
            Environment environment = applicationContext.getEnvironment();
            if (environment.containsProperty(MAVEN_TOMCAT_PORT)) {
                this.port = Long.parseLong(environment.getProperty(MAVEN_TOMCAT_PORT));
            }
        }
        return this.port;
    }

    /***
     * 获取集群服务节点
     * @return
     */
    @Override
    public long getCurrentServerKey() {
        if (this.serverKey == 0) {
            this.serverKey = IPUtils.combineIpAndPort(getHost(), getPort());
        }
        return this.serverKey;
    }

    /***
     * 获取当前节点
     * @return
     */
    @Override
    public SysServer getCurrentSysServer() {
        return getById(getCurrentServerKey());
    }

    /***
     * 获取所有的节点
     * @return
     */
    @Override
    public List<SysServer> getAllServer() {
        return list();
    }

    /***
     * 获取所有在线节点的keys
     * @return
     */
    @Override
    public List<Long> getAllServerKeys() {
        return getBaseMapper().getAllServerKeys();
    }

    /****
     * 随机获取一个节点
     * @return
     */
    @Override
    public long getRandomServerKey() {
        List<Long> activeServers = getAllServerKeys();
        if (activeServers.isEmpty()) {
            return getCurrentServerKey();
        }
        int index = RandomUtils.randomInt(activeServers.size());
        return activeServers.get(index);
    }
}
